package com.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.aop.AuthorizationRequired;
import com.demo.core.constants.HttpStatus;
import com.demo.core.domain.Result;
import com.demo.core.exception.ParameterException;
import com.demo.domain.RegistrationInformation;
import com.demo.domain.TeamProfile;
import com.demo.domain.ro.AddRegInfoRequest;
import com.demo.domain.vo.RegistrationDisplayListView;
import com.demo.service.MessageService;
import com.demo.service.RegistrationInformationService;
import com.demo.utils.PageBean;
import com.demo.websocket.WebSocketServer;
import com.github.pagehelper.PageInfo;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/registration")
public class RegistrationInformationController {
    @Autowired
    private RegistrationInformationService registrationInformationService;

    /**
     * 获取队伍申请信息
     *
     * @param teamId
     * @return
     * @throws IOException
     * @throws ParameterException
     */
    @Operation(summary = "获取队伍的申请信息", description = "根据teamId")
    @GetMapping(value = "/display")
    @ResponseBody
    public Result getRegistration(@RequestParam("teamId") long teamId) throws IOException, ParameterException {
        if (teamId <= 0l) {
            throw new ParameterException("teamId值非法");
        }
        RegistrationInformation registrationInformation = new RegistrationInformation();
        registrationInformation.setRiTeamId(teamId);
        List<RegistrationInformation> registrationInformationList = registrationInformationService.getRegistration(registrationInformation);
        return registrationInformationList != null && !registrationInformationList.isEmpty() ?
                Result.success(HttpStatus.SUCCESS, "查找成功", registrationInformationList) :
                Result.success(HttpStatus.SUCCESS, "No registration information found.", null);
    }

    /**
     * 审核队伍申请
     *
     * @param id
     * @param flag
     * @return
     * @throws ParameterException
     */
    @AuthorizationRequired
    @Operation(summary = "审核队伍申请")
    @PostMapping(value = "/isPass")
    @ResponseBody
    public Result isPassRegistration(@RequestParam("id") long id,
                                     @RequestParam("flag") boolean flag,
                                     HttpServletRequest request) throws ParameterException, IOException {
        if (id < 0l) {
            throw new ParameterException("id数值非法");
        }
        boolean flag1;
        String message;
        if (request == null) {
            throw new ParameterException("request为空");
        }
//        获取当前用户的uid
        Long uid = (Long) request.getAttribute("userId");
        if (flag) {
            flag1 = registrationInformationService.passRegistration(id, uid);
            message = flag1 ? "通过申请成功" : "通过申请失败";
        } else {
            flag1 = registrationInformationService.failRegistration(id, uid);
            message = flag1 ? "拒绝申请成功" : "拒绝申请失败";
        }

        return flag1 ? Result.success(HttpStatus.SUCCESS, message, null)
                : Result.error(message);
    }

    //    提交报名信息
    @AuthorizationRequired
    @RequestMapping("/addRegInf")
    public Result<AddRegInfoRequest> addRegInfController(@RequestBody AddRegInfoRequest addRegInfoRequest, HttpServletRequest request) throws Exception {
        if (addRegInfoRequest == null) {
            throw new ParameterException("registrationInformation为空");
        }
        if (request == null) {
            throw new ParameterException("request为空");
        }
        Long uid = (Long) request.getAttribute("userId");
        AddRegInfoRequest result = registrationInformationService.addRegInf(addRegInfoRequest, uid);
        if (result != null) {
            return Result.success(HttpStatus.SUCCESS, "报名成功!", result);
        } else {
            return Result.error(HttpStatus.SYSTEM_ERROR,
                    "报名失败！");
        }
    }

    /*
     报名表相关的增删查改
    * */
    //    @AuthorizationRequired
    @Operation(summary="根据id找报名信息")
    @GetMapping("/search")
    public Result getByRiId(@RequestParam("riId") Long riId) throws ParameterException {
        return Result.success(HttpStatus.SUCCESS,"查找成功",registrationInformationService.getByRiId(riId));
    }

    @Operation(summary="新增报名信息")
    @PostMapping("/add")
    public Result add(@RequestBody RegistrationInformation registrationInformation) throws ParameterException {
        Integer rows =  registrationInformationService.insertRegistrationInformation(registrationInformation);
        return rows > 0 ? Result.success("添加报名信息成功"):Result.error("添加报名信息失败");
    }

    @Operation(summary="修改报名信息")
    @PostMapping("/edit")
    public Result edit(@RequestBody RegistrationInformation registrationInformation) throws ParameterException {
        int rows = registrationInformationService.updateRegistrationInformation(registrationInformation);
        return rows > 0 ? Result.success("修改报名信息成功"):Result.error("修改报名信息失败");
    }


    @Operation(summary="删除报名信息")
    @PostMapping ("/delete")
    public Result remove(@RequestBody List<RegistrationInformation> registrationInformations) throws ParameterException {
        int row = 0;
        int length = registrationInformations.size();
        for(RegistrationInformation registrationInformation:registrationInformations){
            row += registrationInformationService.deleteRegistrationInformationById(registrationInformation);
        }
        return row ==length ? Result.success("删除报名信息成功") : Result.error("删除报名信息失败");
    }

    @GetMapping("/page")
    @Operation(summary="分页搜索")
    public  Result page(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize")Integer pageSize,RegistrationInformation registrationInformation) throws ParameterException {
        List<RegistrationInformation> list = null;
        PageBean<RegistrationInformation> info = new PageBean<>();
        if(registrationInformation.getRiUid()!=null || registrationInformation.getRiUnickname()!=null || registrationInformation.getRiRealname()!=null || registrationInformation.getRiContact()!= null ||  registrationInformation.getRiReviewStatus()!=null || registrationInformation.getRiTeamId()!=null){
            list = registrationInformationService.selectRegistrationInformationList(registrationInformation);
        }else{
            list =  registrationInformationService.listAllRegistrationInformation();
        }
        // 对查询结果进行分页处理
        PageInfo<RegistrationInformation> pageInfo = new PageInfo<>(list);
        int total = (int) pageInfo.getTotal();
        // 计算起始索引和结束索引
        int startIndex = (pageNum - 1) * pageSize;
        int endIndex = Math.min(startIndex + pageSize, total);
        // 提取当前页的数据
        List<RegistrationInformation> pageList = list.subList(startIndex, endIndex);
        // 设置 PageBean 对象的属性
        info.setPageList(pageList);
        info.setPageNumber(pageNum);
        info.setPageSize(pageSize);
        info.setTotal(total);
        info.setTotalPage((total + pageSize - 1) / pageSize); // 计算总页数
        return Result.success(info);
    }

}
